package com.jjh.controller;

import com.jjh.annation.UnToken;
import com.jjh.consts.ResEnum;
import com.jjh.consts.Result;
import com.jjh.exception.FileException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/api")
@Slf4j
public class FileController {

    @Value("${img.userImgPath}")
    private String userImgPath;

    @Value("${img.dishImgPath}")
    private String dishImgPath;

    @Value("${img.taocanImgPath}")
    private String taocanImgPath;
    /**
     * 用户头像上传
     * @param file
     * @return
     */
    @UnToken
    @PostMapping("/userimg")
    public Result uploadUserImg(@RequestParam("file") MultipartFile file){
       // System.out.println("用户图片上传:"+file.getOriginalFilename());
        //前缀是user
        String prefix = "user-";
        return uploadImg(file,userImgPath,prefix);
    }

    /**
     * 菜品图片上传
     * @param file
     * @return
     */
    @UnToken
    @PostMapping("/dishimg")
    public Result uploadDishImg(@RequestParam("file")MultipartFile file){
        String prefix = "dish-";
        return uploadImg(file,dishImgPath,prefix);
    }

    /**
     * 套餐图片上传
     * @param file
     * @return
     */
    @UnToken
    @PostMapping("/taocanimg")
    public Result uploadTaocanImg(@RequestParam("file")MultipartFile file){
        String prefix = "taocan-";
        return uploadImg(file,taocanImgPath,prefix);
    }

    /**
     * 用户头像下载
     * @param name
     * @param response
     */
    @UnToken
    @GetMapping("/userimg")
    public void getUserImg(String name, HttpServletResponse response){
        String userImgPath = this.userImgPath + File.separator + name;
        downloadImg(userImgPath,response);
    }

    /**
     * 菜品图片下载
     * @param name
     * @param response
     */
    @UnToken
    @GetMapping("/dishimg")
    public void getDishImg(String name,HttpServletResponse response){
        String dishImgPath = this.dishImgPath + File.separator + name;
        downloadImg(dishImgPath,response);
    }

    /**
     * 套餐图片下载
     * @param name
     * @param response
     */
    @UnToken
    @GetMapping("/taocanimg")
    public void getTaocanImg(String name,HttpServletResponse response){
        String taocanImgPath = this.taocanImgPath + File.separator + name;
        downloadImg(taocanImgPath,response);
    }

    /**
     * 删除用户图片
     * @param name 图片名称
     * @return
     */
    @DeleteMapping("/userimg/{name}")
    public Result deleteUserImg(@PathVariable("name") String name){
        return deleteImg(name,userImgPath);
    }

    /**
     * 删除套餐图片
     * @param name 图片名称
     * @return
     */
    @DeleteMapping("/taocanimg/{name}")
    public Result deleteTaocanImg(@PathVariable("name") String name){
        return deleteImg(name,taocanImgPath);
    }

    /**
     * 删除菜品图片
     * @param name 图片名称
     * @return
     */
    @DeleteMapping("/dishimg/{name}")
    public Result deleteDishImg(@PathVariable("name") String name){
        return deleteImg(name,dishImgPath);
    }




    /**
     * 图片上传公用方法
     * @param file 原始文件
     * @param directoryPath 目录位置
     * @param prefix 前缀
     * @return
     */
    public static Result uploadImg(MultipartFile file,String directoryPath,String prefix){

        String oName = file.getOriginalFilename();
        assert oName != null;
        String suffix = oName.substring(oName.indexOf("."));
        String midfix = String.valueOf(UUID.randomUUID());
        String fileName = prefix+midfix+suffix;

        File directory = new File(directoryPath);
        if(!directory.exists()){
            boolean mkdirs = directory.mkdirs();
            if(!mkdirs){
                throw new RuntimeException("无法创建目录在："+directoryPath);
            }
        }
        String targetPath = directoryPath + File.separator + fileName;

        try {
            file.transferTo(new File(targetPath));
        } catch (IOException e) {
            throw new FileException(ResEnum.FILE_UPLOAD_ERROR,"用户图片上传错误！");
        }
        return Result.ok(fileName);
    }


    /**
     * 图片下载公用方法
     * @param name
     * @param response
     */
    public static void downloadImg(String name,HttpServletResponse response){
        try (InputStream inputStream = new FileInputStream(name);
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            response.setContentType("image/jpeg"); // 设置响应的内容类型为图片
            //response.setHeader("Content-Disposition", "attachment; filename=" + imageName + ".jpg"); // 设置响应的文件名

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            // 处理异常
            throw new FileException(ResEnum.FILE_DOWNLOAD_ERROR,"图片下载错误!");
        }
    }

    /**
     * 删除图片公用方法
     * @param name 图片名称
     * @param path  图片路径
     * @return
     */
    public static Result deleteImg(String name,String path){
          String targetFile = path + File.separator + name;
        File file = new File(targetFile);
        if(!file.exists()){
            return Result.ok("文件不存在");
        }
        boolean delete = file.delete();
        if(!delete){
            log.error("用户头像删除失败！{}",targetFile);
            throw new FileException(ResEnum.FILE_DELETE_ERROR,"用户头像删除失败！");
        }
        return Result.ok("删除成功！");
    }



}









